package com.wisewin.pose.util.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wisewin.pose.config.dto.ResultDTO;
import com.wisewin.pose.config.dto.ResultDTOBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

public class MessagePushUtil {
    final static Logger logger = LoggerFactory.getLogger(MessagePushUtil.class);
    // 订单支付模板id
    public static final String templateId = "T7qz4C_-NNAnbhODMgLggPdsyhfNkySVlUGTwmsnZ2s";

    // 发送消息
    public static ResultDTO sendSubscribeMessage(RestTemplate restTemplate, String touserOpenId, String accessToken, String orderNum,
                                                 String serviceName, String orderTime, String price, String productName) {
        Map<String, Object> map = new HashMap<>();
        map.put("template_id", templateId);
        map.put("page", "pages/my/index");
        map.put("touser", touserOpenId);
        /*订单号 {{number1.DATA}}
        服务项目 {{thing2.DATA}}
        完成时间 {{time3.DATA}}
        订单金额 {{amount4.DATA}}
        商品名称 {{thing5.DATA}}*/
        Map<String, Object> data = new HashMap<>();
        // 订单号
        /*Map<String, String> number1 = new HashMap<>();
        number1.put("value", orderNum.substring(0, 13));
        data.put("number1", number1);*/
        // 服务项目
        Map<String, String> thing2 = new HashMap<>();
        thing2.put("value", serviceName);
        data.put("thing2", thing2);
        // 完成时间
        Map<String, String> time3 = new HashMap<>();
        time3.put("value", orderTime);
        data.put("time3", time3);
        // 订单金额
        Map<String, String> amount4 = new HashMap<>();
        amount4.put("value", price);
        data.put("amount4", "￥" + amount4 + "元");
        // 商品名称
        Map<String, String> thing5 = new HashMap<>();
        thing5.put("value", productName);
        data.put("thing5", thing5);
        // 处理推送消息内容
        map.put("data", data);
        System.out.println("map:" + JSON.toJSONString(map));
        // 发送请求
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken,
                httpEntity, String.class);
        logger.info(response.getBody());
        JSONObject phoneData = JSON.parseObject(response.getBody());
        if (phoneData == null || !"0".equals(phoneData.get("errcode").toString())) {
            return ResultDTOBuilder.failure("1", "发送订阅消息失败", null);
        }
        return ResultDTOBuilder.success();
    }
}
